package com.huike.xingxing.activity;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.huike.xingxing.R;
import com.huike.xingxing.api.Api;
import com.huike.xingxing.bean.Message;
import com.huike.xingxing.fragment.MsgFragment;
import com.huike.xingxing.ui.CircleImageView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


/**
 * 了解界面
 */
public class MsgChatActivity extends BaseActivity implements View.OnClickListener {

    private ImageView iv_title_black;
    private TextView tv_title_txt_black;
    private TextView tv_title_txt_content;
    private ImageView iv_title_right_image;
    private TextView tv_title_right_txt;
    private ListView lv_msg_chat;
    private AdapterView adapterView;

    List<Message.DataBean> beanListView = new ArrayList<>();

    String CurrentImage;
    String uid;
    String TAG = "---";

    RequestQueue requestQueue = null;
    Context context;
    JsonObjectRequest jsonObjectRequest;
    private EditText inputMessage;
    private Button sendMessage;
    private String authtype;
    String username;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_msg_chat);
        context = this;
        initData();
        try {
            getChatMessage();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        initView();
        iniClick();
    }

    private void initData() {
        SharedPreferences sharedPreferences = getSharedPreferences("user_ifno", MODE_PRIVATE);
        CurrentImage = sharedPreferences.getString("head_image", null);
        uid = sharedPreferences.getString("uuid", null);
        authtype = sharedPreferences.getString("data", null);
        username = sharedPreferences.getString("username",null);
        Log.e(TAG, "initData: " + CurrentImage + "  " + uid + " role :" + authtype);
        requestQueue = Volley.newRequestQueue(this);


    }

    private void getChatMessage() throws JSONException {
        JSONObject param = new JSONObject();

        param.put("mine", uid);
        param.put("that", MsgFragment.currentTarget.getId());


        jsonObjectRequest = new JsonObjectRequest(1, Api.locaApi + "/getMessageDetailList",
                param.toString(),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        Gson gson = new Gson();
                        Message message = gson.fromJson(jsonObject.toString(), Message.class);
                        List<Message.DataBean> data = message.getData();
                        for (Message.DataBean d : data) {
                            beanListView.add(d);
                            Log.e(TAG, "onResponse: " + d.toString());
                        }
                        adapterView.notifyDataSetChanged();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {

                    }
                });
        requestQueue.add(jsonObjectRequest);
    }

    private void iniClick() {
        // TODO 返回按钮点击
        iv_title_black.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        // TODO 适配器
        adapterView = new AdapterView();
        lv_msg_chat.setAdapter(adapterView);

    }

    private void initView() {
        iv_title_black = (ImageView) findViewById(R.id.iv_title_black);
        tv_title_txt_black = (TextView) findViewById(R.id.tv_title_txt_black);
        tv_title_txt_content = (TextView) findViewById(R.id.tv_title_txt_content);
        iv_title_right_image = (ImageView) findViewById(R.id.iv_title_right_image);
        tv_title_right_txt = (TextView) findViewById(R.id.tv_title_right_txt);
        lv_msg_chat = findViewById(R.id.lv_msg_chat);

        iv_title_black.setVisibility(View.VISIBLE);
        tv_title_txt_content.setText("聊天");
        inputMessage = (EditText) findViewById(R.id.inputMessage);
        inputMessage.setOnClickListener(this);
        sendMessage = (Button) findViewById(R.id.sendMessage);
        sendMessage.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sendMessage:
                submit();
                break;
        }
    }


    private void submit() {
        // validate
        final String inputMessageString = inputMessage.getText().toString().trim();
        if (TextUtils.isEmpty(inputMessageString)) {
            Toast.makeText(this, "消息不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        Log.e(TAG, "submit: " );

        // TODO validate success, do something
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("message", inputMessageString);
            jsonObject.put("send_uid", uid);
            jsonObject.put("to_uid", MsgFragment.currentTarget.getId());
            jsonObject.put("authtype", authtype);
            Log.e(TAG, "submit: "+jsonObject.toString() );

            JsonObjectRequest request = new JsonObjectRequest(1,
                    Api.locaApi + "/sendMessage",
                    jsonObject.toString(),
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject jsonObject) {
                            Log.e(TAG, "onResponse: "+jsonObject.toString() );
                            String data = null;
                            try {
                                data = jsonObject.getString("data");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            if (data.equals("200")) {
                                Toast.makeText(context, "发送成功", Toast.LENGTH_SHORT).show();
                                Message.DataBean dataBean = new Message.DataBean();
                                dataBean.setAuthtype(authtype);
                                dataBean.setMessage(inputMessageString);
                                dataBean.setSend_uid(Integer.parseInt(uid));
                                dataBean.setTo_uid(MsgFragment.currentTarget.getId());
                                beanListView.add(dataBean);
                                adapterView.notifyDataSetChanged();
                                inputMessage.setText("");

                            } else {
                                Toast.makeText(context, "发送失败", Toast.LENGTH_SHORT).show();
                            }
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            Log.e(TAG, "onResponse: "+volleyError.getMessage() );

                        }
                    });

            requestQueue.add(request);

        } catch (Exception e) {

        }

    }

    class AdapterView extends BaseAdapter {

        @Override
        public int getCount() {
            return beanListView.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            Message.DataBean dataBean = beanListView.get(position);
            if (convertView == null) {
                Log.e(TAG, "getView: "+uid.equals(dataBean.getSend_uid()+""));
                //我发送的
                if(uid.equals(dataBean.getSend_uid()+"")){
                    convertView = View.inflate(MsgChatActivity.this, R.layout.right_layout, null);
                }else {
                    convertView = View.inflate(MsgChatActivity.this, R.layout.msgchat, null);
                }

                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.message.setText(dataBean.getMessage());

            if(uid.equals(dataBean.getSend_uid())){
                Glide.with(context).load(Api.url+CurrentImage).into(holder.image);
            }else {
                Glide.with(context).load(Api.url+MsgFragment.currentTarget.getHead_image()).into(holder.image);

            }


            return convertView;
        }


        public
        class ViewHolder {
            public View rootView;
            public CircleImageView image;
            public TextView message;

            public ViewHolder(View rootView) {
                this.rootView = rootView;
                this.image = (CircleImageView) rootView.findViewById(R.id.image);
                this.message = (TextView) rootView.findViewById(R.id.message);
            }

        }
    }
}
